package com.springmq.mq.controller;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName : MqController
 * @Author : lby
 * @Date: 2021/1/27 15:05
 * @Description : mq测试类
 */
@Slf4j
@RestController
@RequestMapping("/mq")
@AllArgsConstructor
public class MqController {

    private final RabbitTemplate rabbitTemplate;
    private final AmqpAdmin amqpAdmin;

    /**
     * 远程创建交换器以及队列
     */
    @GetMapping("/create-exchange")
    public String createExchange(){
        // 创建交换器
        DirectExchange exchange = new DirectExchange("first-exchange");
        amqpAdmin.declareExchange(exchange);
        // 创建队列
        Queue queue = new Queue("first-queue");
        amqpAdmin.declareQueue(queue);
        // 绑定交换器和队列的关系
        Binding binding = new Binding("first-queue",Binding.DestinationType.QUEUE,"first-exchange","first-exchange",null);
        amqpAdmin.declareBinding(binding);
        return "success";
    }



    /**
     * 远程消息发送测试
     */
    @PostMapping("/send-message")
    public String sendMessage(String message){
        // 交换器(存在队列)
        String exchange="first-exchange";
        // 路由指定的键值(队列下的指定key)
        String routeKey="first-exchange";
        rabbitTemplate.convertAndSend(exchange,routeKey,message);
        return "success";
    }

    /**
     * 接受远程消息测试
     */
    @GetMapping("/receive-message")
    public String receiveMessage(){
        // 存在的队列
        String queueName="first-queue";
        Object receiveMessage = rabbitTemplate.receiveAndConvert(queueName);
        log.info("接受的消息:{}",receiveMessage);
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        Map map=new HashMap();
        map.put("aaaaaa","1231231");
        map.put("fdsafdasf","789156");
        map.forEach((k,v)->{
            log.info("遍历key:{},遍历v:{}",k,v);
        });
        return "success";
    }
}
